#!/usr/bin/env node

const fs = require("fs");
const { execSync } = require("child_process");
const path = require("path");

// Dynamic import for ES module
let chalk;

// Initialize ES modules
async function initializeModules() {
    if (!chalk) {
        chalk = (await import("chalk")).default;
    }
}

/**
 * SDAT-Method 的简单版本更新脚本
 * 用法: node tools/version-bump.js [patch|minor|major]
 */

function getCurrentVersion() {
    const packageJson = JSON.parse(fs.readFileSync("package.json", "utf8"));
    return packageJson.version;
}

async function bumpVersion(type = "patch") {
    await initializeModules();

    const validTypes = ["patch", "minor", "major"];
    if (!validTypes.includes(type)) {
        console.error(
            chalk.red(
                `无效的版本类型: ${type}。请使用: ${validTypes.join(", ")}`
            )
        );
        process.exit(1);
    }

    console.log(chalk.yellow("⚠️  手动版本更新已禁用。"));
    console.log(
        chalk.blue("🤖 此项目使用 semantic-release 进行自动化版本管理。")
    );
    console.log("");
    console.log(chalk.bold("要创建新版本，请使用规范提交:"));
    console.log(chalk.cyan("  feat: 新功能 (小版本更新)"));
    console.log(chalk.cyan("  fix: 错误修复 (补丁版本更新)"));
    console.log(chalk.cyan("  feat!: 破坏性变更 (大版本更新)"));
    console.log("");
    console.log(chalk.dim('示例: git commit -m "feat: 添加新的安装程序功能"'));
    console.log(chalk.dim("然后推送到 main 分支以触发自动发布。"));

    return null;
}

async function main() {
    await initializeModules();

    const type = process.argv[2] || "patch";
    const currentVersion = getCurrentVersion();

    console.log(chalk.blue(`当前版本: ${currentVersion}`));

    // Check if working directory is clean
    try {
        execSync("git diff-index --quiet HEAD --");
    } catch (error) {
        console.error(chalk.red("❌ 工作目录不清洁。请先提交更改。"));
        process.exit(1);
    }

    const newVersion = await bumpVersion(type);

    console.log(chalk.green(`\n🎉 版本更新完成！`));
    console.log(chalk.blue(`📦 ${currentVersion} → ${newVersion}`));
}

if (require.main === module) {
    main().catch((error) => {
        console.error("错误:", error);
        process.exit(1);
    });
}

module.exports = { bumpVersion, getCurrentVersion };
